import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mediapipe_task_vision/pose_landmarker.dart';
import 'package:mediapipe_task_vision/mediapipe_task_vision.dart';
import 'package:mediapipe_task_vision_example/painter/PosePainter.dart';

class PoseImageWidget extends StatefulWidget {
  final String path;

  const PoseImageWidget(this.path, {super.key});

  @override
  State<PoseImageWidget> createState() => _PoseImageWidgetState();
}

class _PoseImageWidgetState extends State<PoseImageWidget>
    implements ResultListener {
  var landmarks;

  @override
  void initState() {
    var config = PoseConfig()
      ..runningMode = "image"
      ..delegate = 1
      ..minPoseDetectionConfidence = 0.5
      ..minPosePresenceConfidence = 0.5
      ..minPoseTrackingConfidence = 0.5
      ..numPoses = 1
      ..outputSegmentationMasks = false;
    MediapipeTaskVision.getInstance.poseLandmarker().init(config);
    MediapipeTaskVision.getInstance.setResultListener(this);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(),
      body: Builder(builder: (c) {
        return InkWell(
            onTapDown: (d) {
              MediapipeTaskVision.getInstance
                  .poseLandmarker()
                  .detect(widget.path);
            },
            child: Stack(children: [
              Image.file(File(widget.path)),
              landmarks != null
                  ? CustomPaint(
                      size: size,
                      painter: PosePainter(
                          landmarks["landmarks"],
                          landmarks["inputImageWidth"],
                          landmarks["inputImageHeight"]))
                  : Container(),
              Positioned(
                  bottom: 0,
                  child: Builder(
                    builder: (BuildContext context) {
                      if (landmarks == null) {
                        return Container();
                      }
                      var leftFoot = (landmarks["landmarks"] as List)[31];
                      var rightFoot = (landmarks["landmarks"] as List)[32];
                      return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            landmarkStr(leftFoot),
                            landmarkStr(rightFoot)
                          ]);
                    },
                  ))
            ]));
      }),
    );
  }

  @override
  void deactivate() {
    MediapipeTaskVision.getInstance.poseLandmarker().close();
    super.deactivate();
  }

  Widget landmarkStr(landmark) {
    return Container(
        padding: const EdgeInsets.all(10),
        child: Text("x:${landmark["x"]} y:${landmark["y"]}"));
  }

  @override
  void onError(String error) {}

  @override
  void onResults(Object results) {
    Map? res = results as Map;
    print(res);
    if (res != null) {
      setState(() {
        landmarks = res;
      });
    }
  }
}
